package isquirrel.util;

public class URL {

	public static String convertDBpediaToWIKIpedia(String dbPediaURL) {
		if (dbPediaURL.lastIndexOf('/') == dbPediaURL.length() - 1) {
			dbPediaURL = dbPediaURL.substring(0, dbPediaURL.length() - 1);
		}

		String wikipediaPage = "http://www.wikipedia.org/wiki/"
				+ dbPediaURL.substring(dbPediaURL.lastIndexOf('/') + 1);
		return wikipediaPage;
	}

	public static String convertWIKIpediaToDBpedia(String u) {
		if (u.lastIndexOf('/') == u.length() - 1) {
			u = u.substring(0, u.length() - 1);
		}

		String dbPediaPage = "http://dbpedia.org/resource/"
				+ u.substring(u.lastIndexOf('/') + 1);
		return dbPediaPage;
	}

	public static String constructDBpediaPage(String subject) {
		if (subject == null || subject.length() == 0)
			return null;
		StringBuilder s = new StringBuilder(subject);

		while (s.length() > 0 && s.lastIndexOf(" ") == s.length() - 1)
			// remove spaces at the end of the string
			s.deleteCharAt(s.length() - 1);

		while (s.length() > 0 && s.charAt(0) == ' ') {
			s.deleteCharAt(0);
		}

		s.setCharAt(0, Character.toUpperCase(s.charAt(0)));
		for (int i = 1; i < s.length(); ++i) {
			if (s.charAt(i) == ' ') {
				s.setCharAt(i, '_');
				if (i + 1 < s.length()) {
					s.setCharAt(i + 1, Character.toUpperCase(s.charAt(i + 1)));
				}
			}
		}

		return "http://dbpedia.org/resource/" + s.toString();
	}

	public static String getTitle(String wikipediaPage) {
		if (wikipediaPage.lastIndexOf('/') == wikipediaPage.length() - 1) {
			wikipediaPage = wikipediaPage.substring(0,
					wikipediaPage.length() - 1);
		}

		StringBuilder title = new StringBuilder(wikipediaPage
				.substring(wikipediaPage.lastIndexOf('/') + 1));
		
		for (int i = 0; i < title.length(); ++i) {
			if (title.charAt(i) == '_') {
				title.setCharAt(i, ' ');
			}
		}
		return title.toString();
	}
}